# -*- coding: UTF-8 -*-
'''
发送邮件
小五义：http://www.cnblogs.com/xiaowuyi
'''
import os
import smtplib  
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart

mail_host="smtp.qq.com:25"  #设置服务器
mail_user="2355639223"    #用户名
mail_pass="#abc123"   #口令 
mail_postfix="qq.com"  #发件箱的后缀

def send_mail(to_list,sub,content, type):  
    me=mail_user+"@"+mail_postfix  
    msg = MIMEText(content,_subtype=type,_charset='gb2312')  
    msg['Subject'] = sub  
    msg['From'] = me  
    msg['To'] = to_list; # ";".join(to_list)  
    try:  
        server = smtplib.SMTP()  
        server.connect(mail_host)  
        server.login(mail_user,mail_pass)  
        server.sendmail(me, to_list, msg.as_string())  
        server.close()  
        return True  
    except Exception as e:  
        print(str(e))
        return False  

def send_attach(to_list, sub, attach):
    #创建一个带附件的实例
    msg = MIMEMultipart()

    #构造附件1
    att1 = MIMEText(open(attach, 'rb').read(), 'base64', 'gb2312')
    att1["Content-Type"] = 'application/octet-stream'
    #这里的filename可以任意写，写什么名字，邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename='+os.path.basename(attach)
    msg.attach(att1)

    #构造附件2
#    att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
#    att2["Content-Type"] = 'application/octet-stream'
#    att2["Content-Disposition"] = 'attachment; filename="123.txt"'
#    msg.attach(att2)

    #加邮件头
    #msg['to'] = ";".join(to_list)
    msg['to'] = to_list
    msg['from'] = mail_user+"@"+mail_postfix
    msg['subject'] = sub
    #发送邮件
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user,mail_pass)#XXX为用户名，XXXXX为密码
        server.sendmail(msg['from'], msg['to'],msg.as_string())
        server.quit()
        print ('发送附件成功')
        return True
    except Exception as e:  
        print(str(e))
        return False
    
if __name__ == '__main__':  
    mailto_list='2355639233@qq.com'
    if send_mail(mailto_list,"hello","hello world！", 'plain'):  
        print("发送plain email成功")
    else:  
        print("发送plain email失败")
    if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五义</a>",'html'):
        print ("send html mail success!")
    else:
        print("send html mail fail!")
    if send_attach(mailto_list, "hello", "e:\\python\\hello.py"):
        print("send attach success!")
    else:
        print("send attach fail!")
